package easy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class leetcode350_01 {
    /*
        两个数组的交集
        给定两个数组，编写一个函数计算他们的交集
     */
    public static void main(String[] args) {
        System.out.println(Arrays.toString(intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
    }

    public static int[] intersect(int[] nums1, int[] nums2) {
        //对较短的数组进行操作能优化效率
        if (nums1.length > nums2.length){
            return intersect(nums2,nums1);
        }
        HashMap<Integer, Integer> hm = new HashMap<>();
        for (int i : nums1) {
            if (hm.containsKey(i)) {
                hm.put(i, hm.get(i) + 1);
            } else {
                hm.put(i, 1);
            }
        }
        ArrayList<Integer> list = new ArrayList<>();
        for (int i : nums2) {
            if (hm.containsKey(i)) {
                if (hm.get(i) != 0){
                    list.add(i);
                    hm.put(i,hm.get(i) - 1);
                }
            }
        }
        int[] result = new int[list.size()];
        int index = 0;
        for (Integer i : list) {
            result[index++] = i;
        }
        return result;
    }
}
